package com.cskaoyan.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {

    public static SqlSession getSqlSession() {
        // 0. 获取SqlSessionFactory对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        // 通过类加载器获取文件流
        // InputStream inputStream = MybatisUtils.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        SqlSessionFactory sqlSessionFactory = builder.build(inputStream);

        // 1. 获取连接对象（Connection -----> SqlSession ）
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        return sqlSession;
    }
}
